package com.tian.arch.function.permission

import androidx.fragment.app.Fragment

class FragmentPermissionRequest(private val fragment: Fragment) : PermissionRequest() {
    private var reqFragment: IRequestPermission? = null
    override fun shouldShowRequestPermissionRationale(vararg permission: String): Boolean {
        permissions?.forEach {
            if (!fragment.shouldShowRequestPermissionRationale(it)) {
                return false
            }
        }
        return true
    }

    override fun provideContext() = fragment.requireContext()

    override fun requestPermissions() {
        if (reqFragment == null) {
            reqFragment = RealReqPermissionFragment()
            val fragmentManager = when {
                fragment.parentFragment != null -> fragment.requireParentFragment().childFragmentManager
                fragment.activity != null -> fragment.requireActivity().supportFragmentManager
                else -> throw RuntimeException("$fragment has not attach to activity")
            }
            fragmentManager.beginTransaction().add(reqFragment as Fragment, "RealReqPermissionFragment").commitNowAllowingStateLoss()
        }
        permissions?.let { reqFragment?.reqPermissions(*it) }
    }

    override fun openAppSetting() {
        reqFragment?.openAppSetting()
    }
}